<?php

class SeoHelper extends Helper
{
    
    public function getAliasUrl($alias)
    {
        if (trim($alias) == '') return $alias;
        $alias = StringHelper::translit($alias);
        $alias = preg_replace('|[^a-zA-ZА-Яа-я0-9-]|', '', $alias);
        $alias = strtolower($alias);
        return $alias;
    }
    
    public function getUniqueAliasDB($alias, $table, $field, $addSql = '')
    {
        $count = Yii::app()->db->createCommand("SELECT COUNT(*) FROM $table WHERE `$field` = '$alias' $addSql")->queryScalar();
        if ((int) $count) 
            return SeoHelper::getUniqueAliasDB($alias.'-', $table, $field, $addSql);
        else
            return $alias;
    }
    
    
    public function textClean($text)
    {
        $text = preg_replace('|<script[^>]*?>.*?</script>|si', ' ', $text);
        $text = preg_replace('|<style[^>]*?>.*?</style>|si', ' ', $text);
        $cleanSymbol = array("\n", "\r", "\t", '`', '"', '>', '<');
        $text = html_entity_decode($text);
        $text = str_replace($cleanSymbol, ' ', strip_tags($text));
        //$text = preg_replace('|[\s]{1,}|si', ' ', $text);
        return trim($text);
    }    
    
    public function getDescription($content, $endSymbol = '.', $size = 300)
    {
        $content = SeoHelper::textClean($content); 
        if (function_exists('mb_substr')) {
            $length = mb_strripos(mb_substr($content, 0, $size, 'utf-8'), $endSymbol);
            return mb_substr($content, 0, $length, 'utf-8');
        }
        else {
            $length = strripos(substr($content, 0, $size), $endSymbol);
            return substr($content, 0, $length);
        }
    }
    
    public function getKeywords($content, $count = 80)
    {
        //return '';
        $content = SeoHelper::textClean($content); 
        if (function_exists('mb_strtolower')) {
            $content = mb_strtolower($content, 'utf-8');
        } else {
            $content = strtolower($content);            
        }
        preg_match_all('|[a-zA-Zа-яА-Я]{3,}|ui', $content, $buff);
        $buff = $buff[0];
        if (!count($buff)) return '';
        array_unique($buff);
        $words = array_count_values($buff);
        $words = array_keys($words);
        $keyWordsStopList = str_replace(array("\t", "\n", "\r"), '', Yii::app()->params['keywordsStopList']);
        $keyWordsStopList = str_replace(array(', ', ' ,'), ',', $keyWordsStopList);
        $keyWordsStopList = explode(',', $keyWordsStopList);
        if (count($keyWordsStopList)) $words = array_diff($words, $keyWordsStopList);
        $words = array_slice($words, 0, $count);   
        if (count($words) > 0) {
            return implode(', ', $words);
        } 
    }
}

